package com.raymond.queue.client.codec.decoding;

import cn.hutool.core.util.ByteUtil;
import com.raymond.queue.common.codec.annotation.MsgCodec;
import com.raymond.queue.common.codec.decoding.BaseDecoder;
import com.raymond.queue.common.enums.CommandIdType;
import com.raymond.queue.common.msg.BaseAgreement;
import com.raymond.queue.common.msg.response.ConsumptionMsgResponse;
import com.raymond.queue.common.msg.response.ProductionMsgResponse;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;

import java.util.ArrayList;
import java.util.List;

/**
 * 消费者响应解码器
 *
 * @author :  raymond
 * @version :  V1.0
 * @date :  2021-07-14 11:39
 */
@MsgCodec(commandId = CommandIdType.CONSUMPTION_RESP)
public class ConsumptionMsgResponseDecoder extends BaseDecoder {

    @Override
    public void decode(ChannelHandlerContext ctx, BaseAgreement msg, List<Object> out) throws Exception {
        ByteBuf bodyBuffer = Unpooled.wrappedBuffer(msg.getBodyBuffer());
        ConsumptionMsgResponse consumptionMsgResponse = new ConsumptionMsgResponse(msg.getSequenceId(), bodyBuffer.readInt());
        int readBodyLen = 4;
        List<byte[]> body = new ArrayList<>();
        while (msg.getBodyLength() - readBodyLen > 0) {
            int len = bodyBuffer.readInt();
            byte[] data = new byte[len];
            bodyBuffer.readBytes(data);
            body.add(data);
            readBodyLen += len + 4;
        }
        consumptionMsgResponse.setData(body);
        out.add(consumptionMsgResponse);
    }
}
